import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Modal, Button, Table, Input, DatePicker, message } from "antd";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import { text_check, post_axios, format_time, add_zero } from "../../utils";
import "./index.scss"

export default function ShellManager(props) {
  dayjs.extend(customParseFormat);
  const { t } = useTranslation();
  const { RangePicker } = DatePicker;
  const { TextArea } = Input;
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [data_list, setData_list] = useState([]);
  const [avm_s, setAvm_s] = useState("");
  // 时间
  let today_time = new Date();
  let year = today_time.getFullYear();
  let month = add_zero(today_time.getMonth() + 1);
  let day = today_time.getDate();
  const [date_stamp, setDate_stamp] = useState([
    new Date(year, month, day, 0, 0),
    new Date(year, month, day, 23, 59, 59),
  ]);

  const time_disabled = (current, partial, info) => {
    return current && current > dayjs().endOf("day");
  };

  const getData = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      avm: avm_s,
      bdate_stamp: format_time(new Date(date_stamp[0]), "obj_date"),
      edate_stamp: format_time(new Date(date_stamp[1]), "obj_date"),
    };
    setSpinning(true);
    let res = await post_axios("shell_manager", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setData_list(res.data_rows.rows);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("platform_manager.avm"),
      dataIndex: "avm",
      align: "center",
    },
    {
      title: t("platform_manager.instructions"),
      dataIndex: "orders",
      align: "center",
      width: 400,
    },
    {
      title: t("platform_manager.remark"),
      dataIndex: "remark",
      align: "center",
      width: 300,
    },
    {
      title: t("platform_manager.operator"),
      dataIndex: "username",
      align: "center",
    },
    {
      title: t("platform_manager.operation_time"),
      dataIndex: "ctime",
      align: "center",
    },
  ];

  const search_data = () => {
    getData(1);
  };

  const shell_quick = [
    {
      msg_cn: "删除数据库",
      msg_en: "delete",
      shell: `{"action":"shell","cmd":"rm -rf /sdcard/android/data/easytouch/"}`,
    },
    {
      msg_cn: "重启",
      msg_en: "reboot",
      shell: `{"action":"shell","cmd":"reboot"}`,
    },
    {
      msg_cn: "home按键",
      msg_en: "home",
      shell: `{"action":"shell","cmd":"input keyevent 3"}`,
    },
    {
      msg_cn: "提取日志",
      msg_en: "note",
      shell: `{"action":"shell","cmd":"log 2023-01-01"}`,
    },
  ];

  const [edit_shell_show, setEdit_shell_show] = useState(false);
  const [edit_avms, setEdit_avms] = useState("");
  const [edit_remark, setEdit_remark] = useState("");
  const [edit_order, setEdit_order] = useState("");
  const edit_customer_dialog_show = () => {
    setEdit_avms("");
    setEdit_remark("");
    setEdit_order("");

    setEdit_shell_show(true);
  };

  const shell_quick_click = (item) => {
    setEdit_order(item.shell);
  };

  const edit_com_confirm = async () => {
    if (edit_remark === "") {
      message.warning({
        content: t("platform_manager.enter_remark"),
      });
      return;
    }

    if (edit_avms === "") {
      message.warning({
        content: t("platform_manager.enter_avm"),
      });
      return;
    }

    let upMsg = {
      avm_s: edit_avms,
      order: edit_order,
      remark: edit_remark,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("shell_manager", "m_add", upMsg);
    if (!res) return;
    message.success({
      content: t("common.add_scuuess"),
    });
    setEdit_shell_show(false);
    search_data();
  };
  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("shell_manager")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
    });
  }, []);
  return (
    <>
      <div className="shell_manager modules">
        <div className="screen_ipt">
          <div className="ipt_box normal_title">
            <div className="ipt_box_title">{t("platform_manager.avm")}</div>
            <Input
              placeholder=" "
              value={avm_s}
              size="small"
              onChange={(e) => setAvm_s(e.target.value)}
            />
          </div>
          <div className="ipt_box date_title">
            <div className="ipt_box_title">{t("system_manager.time")}</div>
            <RangePicker
              size="small"
              disabledDate={time_disabled}
              onChange={(date, dateString) => {
                setDate_stamp(date);
              }}
            />
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={edit_customer_dialog_show}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div className="page-table">
            <Table
              dataSource={data_list}
              size="small"
              bordered
              columns={columns}
              rowKey="id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              pagination={false}
            />
          </div>
        </div>
      </div>
      <Modal
        title={t("common.add")}
        open={edit_shell_show}
        classNames={{
          body: "edit_dialog_body shell_manager_dialog",
          wrapper:"edit_800_style"
        }}
        onOk={edit_com_confirm}
        onCancel={() => setEdit_shell_show(false)}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box dialog_ipt_box_long normal_title">
          <div className="ipt_box_title">{t("platform_manager.remark")}</div>
          <TextArea
            placeholder=" "
            value={edit_remark}
            onChange={(e) => setEdit_remark(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box dialog_ipt_box_long normal_title">
          <div className="ipt_box_title">{t("platform_manager.avm")}</div>
          <TextArea
            placeholder=" "
            value={edit_avms}
            onChange={(e) => setEdit_avms(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box dialog_ipt_box_long normal_title">
          <div className="ipt_box_title">
            {t("platform_manager.instructions")}
          </div>
          <TextArea
            placeholder=" "
            value={edit_order}
            onChange={(e) => setEdit_order(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box dialog_ipt_box_long buttonBox">
          {shell_quick.map((item) => {
            return (
              <Button
                type="primary"
                style={{margin:"0 10px"}}
                key={item}
                onClick={() => shell_quick_click(item)}
              >
                {text_check(item)}
              </Button>
            );
          })}
        </div>
      </Modal>
    </>
  );
}
